<template>
  <div class="app-container">
    <!-- 操作栏 -->
    <div class="buttons">
      <el-button type="primary" icon="el-icon-plus" @click="add"
        >新增</el-button
      >
    </div>
    <div class="mod-result-table">
      <HTable
        ref="table"
        :tableData="TableData"
        :columnConfigs="columnConfigs"
        @selection-change="handleSelectionChange"
        :selectable="false"
        orderable
        v-loading="loading"
        :pages="pagination"
        @page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <template slot-scope="{ row }">
          <template v-if="row.name == 'action'">
            <el-button
              type="text"
              size="small"
              icon="el-icon-edit"
              @click="edit(row.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              icon="el-icon-delete"
              size="small"
              @click="handleDelete(row.row)"
              >删除</el-button
            >
          </template>
          <template v-else-if="row.name == 'color'">
            <el-tag
              :style="{
                color: '#fff',
                backgroundColor: row.row.color,
                borderColor: row.row.color,
              }"
              effect="plain"
            >
              {{ row.row.color }}
            </el-tag>
          </template>
          <template v-else-if="row.name == 'size'">
            {{ row.row.size && row.row.size + "px" }}
          </template>
          <template v-else-if="row.name == 'rotation'">
            {{ row.row.rotation && row.row.rotation + "°" }}
          </template>
          <template v-else-if="row.name == 'transparency'">
            {{ row.row.transparency && formatTrancy(row.row.transparency) }}
          </template>
        </template>
      </HTable>
    </div>
    <div class="vpnform">
      <el-dialog
        :title="editFlag ? '编辑水印' : '新增水印'"
        class="addDialog"
        :visible.sync="dialogVisible1"
        :before-close="handleClose"
        :close-on-click-modal="false"
        width="55%"
      >
        <el-form
          ref="addform"
          :model="vpnform"
          :rules="rulesVpnform"
          label-width="110px"
        >
          <el-form-item label="资源地址:" prop="host">
            <el-input
              v-model="vpnform.host"
              maxlength="64"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="水印内容:" prop="content">
            <el-input
              v-model="vpnform.content"
              maxlength="256"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="宽度:" prop="width">
            <el-input
              v-model="vpnform.width"
              maxlength="8"
              placeholder="请输入数字"
            >
              <template slot="append">px</template></el-input
            >
          </el-form-item>
          <el-form-item label="高度:" prop="height">
            <el-input
              v-model="vpnform.height"
              maxlength="8"
              placeholder="请输入数字"
            >
              <template slot="append">px</template></el-input
            >
          </el-form-item>
          <el-form-item label="字体:" prop="font">
            <el-select v-model="vpnform.font" placeholder="请选择字体">
              <el-option
                v-for="item in fontOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="水印颜色:" prop="color">
            <el-color-picker v-model="vpnform.color"></el-color-picker>
            <!-- <Sketch
              @input="handleChange"
              :show-alpha="true"
              :value="colors"
            ></Sketch> -->
          </el-form-item>
          <el-form-item class="slider" label="水印大小:" prop="size">
            <el-slider
              v-model="vpnform.size"
              :min="0"
              :max="100"
              :format-tooltip="formatTooltipSize"
            ></el-slider>
            <!-- <el-input
              v-model="vpnform.size"
              maxlength="8"
              placeholder="请输入数字"
            ></el-input> -->
          </el-form-item>
          <el-form-item class="slider" label="旋转角度:" prop="rotation">
            <el-slider
              v-model="vpnform.rotation"
              :min="0"
              :max="100"
              :format-tooltip="formatTooltipRotation"
            ></el-slider>
            <!-- <el-input
              v-model="vpnform.rotation"
              maxlength="8"
              placeholder="请输入数字"
            ></el-input> -->
          </el-form-item>
          <el-form-item class="slider" label="透明度:" prop="transparency">
            <!-- <el-input
              v-model="vpnform.transparency"
              maxlength="8"
              placeholder="请输入"
            ></el-input> -->
            <el-slider
              v-model="vpnform.transparency"
              :min="0"
              :max="100"
              :format-tooltip="formatTooltip"
            ></el-slider>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取 消</el-button>
          <el-button type="primary" @click="submitaddForm('addform')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import table from "@/mixins/commontable";
import { Sketch } from "vue-color";
import { columnConfigs } from "./columnConfigs.js";
import { addList, editList, getList, delCurRow } from "@/api/yybl/watermark";
import { validateIpPort } from "@/utils/validate";
export default {
  components: {
    Sketch,
  },
  mixins: [table], //表格的混入，主要包括表格上通用的方法和数据，比如查询，重置，分页这些功能
  props: {},
  data() {
    let checkTransparency = (rex, value, callback) => {
      // if (!value) {
      //   return callback(new Error('年龄不能为空'));
      // }
      // const rule = new RegExp("^0.\d$");
      const rule = /^0.\d+$/;
      if (rule.test(value) || value == 0 || value == 1) {
        callback();
      } else {
        callback(new Error("透明度范围为0-1"));
      }
    };
    let checkNumber = (rex, value, callback) => {
      // if (!value) {
      //   return callback(new Error('年龄不能为空'));
      // }
      // const rule = new RegExp("^0.\d$");
      const rule = /^\d*$/;
      if (rule.test(value)) {
        callback();
      } else {
        callback(new Error("请输入数字"));
      }
    };
    return {
      colors: {
        // hex: "#194d33",
        // hex8: "#194D33A8",
        // hsl: { h: 150, s: 0.5, l: 0.2, a: 1 },
        // hsv: { h: 150, s: 0.66, v: 0.3, a: 1 },
        // rgba: { r: 25, g: 77, b: 51, a: 1 },
        // a: 1,
      },
      columnConfigs,
      dialogVisible1: false,
      editFlag: false,
      fontOptions: [
        {
          value: "微软雅黑",
          label: "微软雅黑",
        },
        {
          value: "宋体",
          label: "宋体",
        },
        {
          value: "仿宋",
          label: "仿宋",
        },
        {
          value: "黑体",
          label: "黑体",
        },
        {
          value: "楷体",
          label: "楷体",
        },
        {
          value: "等线",
          label: "等线",
        },
      ],
      vpnform: {
        // rotation: new Number(),
        // size: new Number(),
      },
      rulesVpnform: {
        host: [
          { required: true, message: "请输入资源地址", trigger: "blur" },
          { validator: validateIpPort, trigger: "blur" },
          // { type: "number", message: "大小必须为数字值" },
        ],
        content: [
          { required: true, message: "请输入水印内容", trigger: "blur" },
          // { type: "number", message: "大小必须为数字值" },
        ],
        font: [
          { required: true, message: "请选择字体", trigger: "change" },
          // { type: "number", message: "大小必须为数字值" },
        ],
        size: [
          { validator: checkNumber, trigger: "blur" },
          { required: true, message: "请输入水印大小" },
          // { type: "number", message: "大小必须为数字值" },
        ],
        rotation: [
          { validator: checkNumber, trigger: "blur" },
          { required: true, message: "请输入旋转角度" },
          // { type: "number", message: "角度必须为数字值" },
        ],
        width: [
          { validator: checkNumber, trigger: "blur" },
          { required: true, message: "请输入宽度" },
          // { type: "number", message: "大小必须为数字值" },
        ],
        height: [
          { validator: checkNumber, trigger: "blur" },
          { required: true, message: "请输入高度" },
          // { type: "number", message: "大小必须为数字值" },
        ],
        transparency: [
          // { validator: checkTransparency, trigger: "blur" },
          { required: true, message: "请输入透明度", trigger: "blur" },
        ],
      },
      computers: [],
      vpntypes: [],
      curRow: {},
    };
  },
  watch: {},
  computed: {
    TableData() {
      const deshuiyin = (con) => {
        let a = con.replace(/\\([\<\>\'\"\\])/g, (d, b) => {
          return `${b}`;
        });
        return a;
      };
      let list = this.tableData.map((i) => {
        let val = deshuiyin(i.content);
        return {
          ...i,
          content: val,
        };
      });
      return list;
    },
  },
  methods: {
    formatTrancy(val) {
      let a = Number(val);
      return Math.round(a * 100) + "%";
    },
    formatTooltip(val) {
      return val + "%";
    },
    formatTooltipRotation(val) {
      return val + "°";
    },
    formatTooltipSize(val) {
      return val + "px";
    },
    handleChange(val) {
      console.log(val);
    },
    add() {
      this.editFlag = false;
      this.$nextTick(() => {
        this.dialogVisible1 = true;
        this.$refs?.addform?.clearValidate();
      });
      this.vpnform = {
        host: "",
        content: "",
        rotation: 15,
        size: 16,
        font: "微软雅黑",
        color: "#f0f0f0",
        width: "250",
        height: "150",
        transparency: 50,
      };
      this.$refs?.addform?.clearValidate();
    },
    edit(row) {
      this.editFlag = true;
      this.dialogVisible1 = true;
      this.curRow = row;
      this.curRow.transparency = Number(this.curRow.transparency);
      this.curRow.rotation = Number(this.curRow.rotation);
      this.curRow.size = Number(this.curRow.size);
      const {
        host,
        content,
        size,
        rotation,
        font,
        color,
        width,
        height,
        transparency,
      } = row;
      this.vpnform = {
        host,
        content,
        size,
        rotation,
        font,
        color,
        width,
        height,
        transparency: Math.round(transparency * 100),
      };
      this.$refs?.addform?.clearValidate();
    },
    async handleDelete(row) {
      this.$confirm("此操作将删除数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let ids;
          if (row) ids = row.watermarkId;
          const res = await delCurRow({
            ids: ids,
          });
          if (res.rescode == "200") {
            this.$message.success("删除成功");
            this.refresh();
          } else this.$message.error(res.msg);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    submitaddForm(val) {
      console.log(val);
      this.$refs["addform"].validate((val) => {
        if (val) {
          console.log("通过校验");
          const {
            host,
            content,
            size,
            rotation,
            font,
            color,
            width,
            height,
            transparency,
          } = this.vpnform;
          let a = content.replace(/[\<\>\'\"\\]/g, (a, b, c) => {
            return `\\${a}`;
          });
          let transparencyval = transparency / 100;
          let params = {
            host,
            content: a,
            size,
            rotation,
            font,
            color,
            width,
            height,
            transparency: transparencyval,
          };
          // params.userId = null;
          // params.sharedkey = encode(form.sharedkey);
          if (this.editFlag) {
            params.watermarkId = this.curRow.watermarkId;
            editList(params)
              .then((res) => {
                if (res.rescode == 200) {
                  this.dialogVisible1 = false;
                  this.$message.success("编辑成功");
                  this.refresh();
                } else {
                  this.$message.error(res.msg);
                }
              })
              .catch((err) => {
                console.log(err);
              });
          } else {
            // 调用新增接口
            addList(params)
              .then((res) => {
                if (res.rescode == 200) {
                  this.dialogVisible1 = false;
                  this.$message.success("新增成功");
                  this.refresh();
                } else {
                  this.$message.error(res.msg);
                }
              })
              .catch((err) => {
                console.log(err);
              });
          }
        } else {
          console.log("校验失败");
        }
      });
    },
    handleClose() {
      this.dialogVisible1 = false;
    },
    handleSelectionChange() {},
    refresh() {
      this.getlists(getList, {});
    },
  },
  created() {
    this.refresh();
  },
  mounted() {},
};
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__content {
  .el-date-editor.el-input {
    width: 100%;
  }
}
::v-deep .el-button {
  .el-icon-edit + span {
    margin-left: 0px;
  }
  .el-icon-delete + span {
    margin-left: 0px;
  }
}
::v-deep .el-dialog {
  .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
  }
  .el-dialog__footer {
    border-top: 1px solid #e8e8e8;
  }
}
.addDialog {
  .el-form {
    .el-form-item.slider {
      width: 100%;
    }
  }
}
</style>
